package user

import (
	handler2 "cms/handler"
	"cms/model"
	service "cms/serivce"
	"engine/cache"
	"engine/dto"
	emodel "engine/model"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/shopspring/decimal"
	"gorm.io/gorm"
	"lib/db"
	flish2 "lib/flish"
	"lib/log"
	"lib/response"
	sferrors "lib/sf-errors"
	"math"
	"strconv"
	"strings"
	"time"
)

type AdHandler struct{}

//	用户登录
//
// @Summary		获取记录
// @Description	获取记录
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Param		RequestBody body model.LoginRequest true "请求参数"
// @Success		200 {object} response.Response[response.AuthResponse[model.SysUser, any]]
// @Router		/api/user/v2/ad [get]
func (handler *AdHandler) AdList(ctx *gin.Context) {
	var newList []emodel.My_advertisement
	err := db.GetDb().Find(&newList).Error
	if err != nil {
		response.Error(ctx, err)
		return
	}
	var newData = model.AdvertisementResp{}
	for _, i2 := range newList {
		if i2.Type == 0 {
			newData.Ad = append(newData.Ad, i2)
		} else {
			newData.Ad1 = append(newData.Ad1, i2)
		}
	}
	response.OkData(ctx, newData)
	return
}

//	用户登录
//
// @Summary		投放广告
// @Description	投放广告
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Param		RequestBody body model.LoginRequest true "请求参数"
// @Success		200 {object} response.Response[response.AuthResponse[model.SysUser, any]]
// @Router		/api/user/v2/ad [post]
func (handler *AdHandler) AdCreate(ctx *gin.Context) {
	id := ctx.Param("id")
	if id == "" {
		response.Error(ctx, sferrors.Code(sferrors.ErrorBadRequest))
		return
	}
	aId, err := strconv.Atoi(id)
	if err != nil {
		response.Error(ctx, sferrors.Code(sferrors.ErrorBadRequest))
		return
	}

	var reqData model.AdvertisementReq
	if err = ctx.ShouldBind(&reqData); err != nil {
		response.Error(ctx, sferrors.Code(sferrors.ErrorBadRequest))
		return
	}

	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}

	if operator.N == 0 {
		err = service.CheckOpenid(reqData.Authcode, operator.My_user)
		if err != nil {
			response.Error(ctx, sferrors.NewStringf("请重新授权： "+err.Error()))
			return
		}
	}

	var adInfo *emodel.My_advertisement
	err = db.GetDb().First(&adInfo, aId).Error
	if err != nil {
		response.Error(ctx, err)
		return
	}
	if adInfo == nil {
		response.Error(ctx, sferrors.NewStringf("非法操作！"))
		return
	}

	//dayts

	err = db.GetDb().Transaction(func(tx *gorm.DB) error {
		var myUser emodel.My_user
		txErr := tx.Where("id=?", operator.Id).First(&myUser).Error
		if txErr != nil {
			return txErr
		}
		if myUser.Money < adInfo.Money {
			return sferrors.NewStringf("您的 通用积分 余额不足")
		}
		txErr = service.CreateUserLog(tx, myUser, adInfo.Money, 0, myUser.Id, "投放广告【"+adInfo.Title+"】")
		if txErr != nil {
			return txErr
		}

		newData := emodel.My_advertisement_user{
			Uid:     operator.Id,
			Mobile:  myUser.Mobile,
			Title:   reqData.Title,
			Type:    adInfo.Type,
			Content: reqData.Content,
			Image:   reqData.Image,
			Icon:    reqData.Icon,
			Num:     adInfo.Num,
			SyNum:   adInfo.Num,
			Money:   adInfo.Money,
		}
		txErr = tx.Omit("create_time").Create(&newData).Error
		if txErr != nil {
			return txErr
		}
		return nil
	})
	if err != nil {
		response.Error(ctx, err)
		return
	}
	response.OkData[string](ctx, "操作成功")
}

// GetAdListUser 我的广告列表
// @Summary		我的广告列表
// @Description	我的广告列表
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Param		RequestQuery query model.QueryUserLogRequest true "Request Parameters"
// @Success		200 {object} response.Response[dto.PaginationList[emodel.SysUserLog]]
// @Router		/api/user/v2/ad/{PAGE} [GET]
func (handler *AdHandler) GetAdListUser(ctx *gin.Context) {
	//
	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}

	page := ctx.Param("page")
	pageInt, err := strconv.Atoi(page)
	if err != nil {
		response.Error(ctx, err)
		return
	}
	types := ctx.Param("type")

	if pageInt == 0 {
		pageInt = 1
	}
	query := db.GetDb()
	query = query.Where("uid=?", operator.Id)

	switch types {
	case "0":
		query = query.Where("status=?", "0")
	case "1":
		query = query.Where("status=?", "1")
	case "2":
		query = query.Where("status=?", "2")
	case "3":
		query = query.Where("sy_num<=0")
	}

	query = query.Order("sy_num desc,id asc")

	list, err := dto.Paginate[emodel.My_advertisement_user](query, &dto.PaginatorOption{
		Page:     pageInt,
		PageSize: 8,
		ShowSQL:  true,
	})

	response.OkData(ctx, list)
}

// GetAdInfo 查看广告
// @Summary		查看广告
// @Description	查看广告
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Param		RequestQuery query model.QueryUserLogRequest true "Request Parameters"
// @Success		200 {object} response.Response[dto.PaginationList[emodel.SysUserLog]]
// @Router		/api/user/v2/ad-now/{type} [GET]
func (handler *AdHandler) GetAdInfo(ctx *gin.Context) {
	response.OkData(ctx, model.AdResp{
		Id:   0,
		Icon: "",
	})
	return
	types := ctx.Param("type")
	query := db.GetDb()
	if types == "home" {
		query.Where("type=1")
	} else if types == "start" {
		query.Where("type=0")
	} else {
		response.Error(ctx, sferrors.Code(sferrors.ErrorBadRequest))
		return
	}
	query = query.Select("id", "icon")
	query = query.Where("sy_num>0 and status=1")
	query = query.Order("RAND()")
	dataInfo := &emodel.My_advertisement_user{}
	query.First(&dataInfo)

	db.GetDb().Exec("update my_advertisement_user set sy_num=sy_num-1 where id=? ", dataInfo.Id)

	response.OkData(ctx, model.AdResp{
		Id:   dataInfo.Id,
		Icon: dataInfo.Icon,
	})
}

// GetAdInfoId 查看广告详情
// @Summary		查看广告详情
// @Description	查看广告详情
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Param		RequestQuery query model.QueryUserLogRequest true "Request Parameters"
// @Success		200 {object} response.Response[dto.PaginationList[emodel.SysUserLog]]
// @Router		/api/user/v2/ad-now-dea/{id} [GET]
func (handler *AdHandler) GetAdInfoId(ctx *gin.Context) {

	id := ctx.Param("id")
	query := db.GetDb()

	query = query.Select("content", "image", "title")
	query = query.Where("id=?", id)
	dataInfo := &emodel.My_advertisement_user{}
	query.Debug().First(&dataInfo)

	response.OkData(ctx, model.AdRespList{
		Image:   dataInfo.Image,
		Title:   dataInfo.Title,
		Content: dataInfo.Content,
	})
}

func (handler *AdHandler) GetAddress(ctx *gin.Context) {
	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}
	page := ctx.Param("page")
	pageInt, err := strconv.Atoi(page)
	if err != nil {
		response.Error(ctx, err)
		return
	}
	pageSize := 6

	query := db.GetDb().Where("user_id=?", operator.Id).Order("id desc")
	list, err := dto.Paginate[emodel.My_user_address](query, &dto.PaginatorOption{
		Page:     pageInt,
		PageSize: pageSize,
	})
	if err != nil {
		log.Errorf("获取记录失败：%v", err)
		response.Error(ctx, sferrors.New(err).SetCode(sferrors.SystemError))
		return
	}

	response.OkData(ctx, list)
}
func (handler *AdHandler) GetAddressDetail(ctx *gin.Context) {
	id := ctx.Param("id")
	if id == "" {
		response.Error(ctx, sferrors.Code(sferrors.ErrorBadRequest))
		return
	}

	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}
	var newAddress emodel.My_user_address
	err = db.GetDb().Where("user_id=? and id=?", operator.Id, id).First(&newAddress).Error
	if err != nil {
		response.Error(ctx, err)
		return
	}
	response.OkData(ctx, newAddress)
}

func (handler *AdHandler) CreateAddress(ctx *gin.Context) {
	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}
	var req emodel.My_user_address
	if err := ctx.ShouldBind(&req); err != nil {
		response.Error(ctx, err)
	}
	id := ctx.Param("id")
	if id == "" {
		response.Error(ctx, sferrors.Code(sferrors.ErrorBadRequest))
		return
	}
	if req.IsDefault == true {
		db.GetDb().Table("my_user_address").Where("user_id=?", operator.Id).
			UpdateColumn("is_default", 0)
	}
	if id == "0" {
		req.UserId = operator.Id
		req.Mobile = operator.Mobile
		db.GetDb().Where("id=?", id).Create(&req)

	} else {
		db.GetDb().Where("id=?", id).Updates(&req)
	}
	response.OkData(ctx, "操作成功")
}

func (handler *AdHandler) DeleteAddress(ctx *gin.Context) {
	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}
	id := ctx.Param("id")
	if id == "" {
		response.Error(ctx, sferrors.Code(sferrors.ErrorBadRequest))
		return
	}

	err = db.GetDb().Table("my_user_address").Where("user_id=? and id=?", operator.Id, id).Delete(true).Error
	if err != nil {
		response.Error(ctx, err)
		return
	}
	response.OkData(ctx, "操作成功")
}

// 数量
func (handler *AdHandler) Jijin(ctx *gin.Context) {
	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}
	var ddd emodel.My_create_page
	err = db.GetDb().Select("zb", "xh").Where("id=1").First(&ddd).Error
	if err != nil {
		response.Error(ctx, err)
		return
	}
	type mmm struct {
		Zb    decimal.Decimal `json:"zb"`
		Xh    string          `json:"xh"`
		Money string          `json:"money"`
		DhXh  int             `json:"dh_xh"`
		P1    int             `json:"p1"`
		P2    int             `json:"p2"`
	}

	ss, _ := cache.RedisContextGet[int](ctx, "duihuan")

	p1, _ := cache.RedisContextGet[int](ctx, "p2")
	p2, _ := cache.RedisContextGet[int](ctx, "p1")
	xh1, _ := cache.RedisContextGet[int](ctx, "xh1")

	var xh float64
	db.GetDb().Table("my_order_dea").Where("flag=1 and puid=20231898").Select("SUM(money)").Scan(&xh)
	mmmm := &mmm{
		Zb:    ddd.Zb,
		Xh:    fmt.Sprintf("%.2f", xh+float64(*xh1)),
		Money: fmt.Sprintf("%.2f", operator.Money),
		DhXh:  *ss,
		P1:    *p1,
		P2:    *p2,
	}
	response.OkData(ctx, mmmm)
}

// 数量 i/api/user/v2/flish 我的鱼
func (handler *AdHandler) Flish(ctx *gin.Context) {
	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}

	var ddds []emodel.MyFlish
	err = db.GetDb().Find(&ddds).Error
	if err != nil {
		response.Error(ctx, err)
		return
	}
	dddsss := map[uint64]emodel.MyFlish{}
	for _, d := range ddds {
		dddsss[d.Id] = d
	}

	var ddd []emodel.MyMyFlish
	err = db.GetDb().Select("f", "ycl", "t_days", "sl", "l", "szq").Where("uid=?", operator.Id).Find(&ddd).Error
	if err != nil {
		response.Error(ctx, err)
		return
	}

	mmmLis := make([]*emodel.TaskReqAuthAAA, 0)

	noewDAya := time.Now().Format("20060102")
	noewDAyaInt, _ := strconv.Atoi(noewDAya)
	for _, i2 := range ddd {
		w := 0
		if noewDAyaInt == i2.TDays {
			w = 1
		}
		ddds[i2.F-1].Zq = 365 - i2.Szq
		mmmLis = append(mmmLis, &emodel.TaskReqAuthAAA{
			MyMyFlish: i2,
			Kkk:       ddds[i2.F-1],
			W:         w,
		})
	}
	response.OkData(ctx, mmmLis)
}

// 数量
func (handler *AdHandler) FlishTu(ctx *gin.Context) {

	xindex := ctx.Param("xindex")
	if xindex == "" {
		response.Error(ctx, sferrors.Code(sferrors.ErrorBadRequest))
		return
	}
	xindexIndex, _ := strconv.Atoi(xindex)
	var ddd []emodel.MyFlish
	err := db.GetDb().Where("level=?", xindexIndex*100).Find(&ddd).Error
	if err != nil {
		response.Error(ctx, err)
		return
	}
	response.OkData(ctx, ddd)
}
func (handler *AdHandler) Piao(ctx *gin.Context) {
	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}
	types := ctx.Param("types")
	if types == "" {
		response.Error(ctx, sferrors.Code(sferrors.ErrorBadRequest))
		return
	}
	uidss := strconv.Itoa(int(operator.Id))
	keyss := "duihuancc" + uidss

	mm, err := cache.RedisContextGet[int](ctx, keyss)
	if err == nil && mm != nil {
		response.Error(ctx, sferrors.NewStringf("一个用户只能参与1次"))
		return
	}
	if operator.IsTask == 0 {
		response.Error(ctx, sferrors.NewStringf("有效用户方可参与"))
		return
	}

	//cache.RedisContextSet(ctx, "p1", 0,0)
	//cache.RedisContextSet(ctx, "p2", 0,0)
	p1, _ := cache.RedisContextGet[int](ctx, "p1")
	p2, _ := cache.RedisContextGet[int](ctx, "p2")
	if types == "1" {
		cache.RedisContextSet(ctx, "p1", *p1+1, 0)
	} else {
		cache.RedisContextSet(ctx, "p2", *p2+1, 0)
	}

	cache.RedisContextSet(ctx, keyss, 1, 0)

	response.OkData(ctx, "操作成功")
}

// iapi/user/v2/flish/0 捞鱼
func (handler *AdHandler) BuyuPiao(ctx *gin.Context) {

	nowTime := time.Now().Format("1504")
	IntNow, err := strconv.Atoi(nowTime)

	zhuanStr := "捕捞时间为 1:00到24:00"
	if IntNow > 100 && IntNow < 2400 {
	} else {
		response.Error(ctx, sferrors.NewStringf(zhuanStr))
		return
	}

	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}
	types := ctx.Param("types")
	if types == "" {
		response.Error(ctx, sferrors.Code(sferrors.ErrorBadRequest))
		return
	}
	typesInt, err := strconv.Atoi(types)
	if err != nil {
		response.Error(ctx, sferrors.Code(sferrors.ErrorBadRequest))
		return
	}
	if typesInt != 0 && typesInt != 1 && typesInt != 2 {
		response.Error(ctx, sferrors.Code(sferrors.ErrorBadRequest))
		return
	}
	num := 1
	if typesInt == 1 {
		num = 10
	}

	//我已经有的鱼
	var myMyflish []emodel.MyMyFlish
	err = db.GetDb().Where("uid=? ", operator.Id).Find(&myMyflish).Error
	if err != nil {
		response.Error(ctx, err)
		return
	}
	if len(myMyflish) > 500 {
		response.Error(ctx, sferrors.NewString("暂时最多只能捕捞500条鱼"))
		return
	}

	mmeqqw := db.GetDb()
	flish := make([]emodel.MyFlish, 0, num)
	if len(myMyflish) > 0 {
		idss := []uint64{}
		for _, i2 := range myMyflish {
			idss = append(idss, i2.F)
		}
		mmeqqw = mmeqqw.Where("id not in (?)", idss).Find(&flish)
	}

	err = mmeqqw.Find(&flish).Error
	if err != nil {
		response.Error(ctx, err)
		return
	}

	if len(flish) == 0 {
		response.Error(ctx, sferrors.NewString("没有鱼可以抽了"))
		return
	}
	if len(flish) < num {
		response.Error(ctx, sferrors.NewString(fmt.Sprintf("最多还能捕捞%d个", num)))
		return
	}
	selector := flish2.NewFishSelector(flish)

	mmms := make([]emodel.MyMyFlishSS, 0, num)
	err = db.GetDb().Transaction(func(tx *gorm.DB) error {
		var myUser emodel.My_user
		txErr := tx.Where("id=?", operator.Id).First(&myUser).Error
		if txErr != nil {
			return txErr
		}
		if typesInt == 2 {
			if myUser.Bio != "1" {
				return sferrors.NewStringf("沒有可用券了")
			}
			if err = tx.Exec("update my_user set bio=2 where id=?", myUser.Id).Error; err != nil {
				return err
			}

		} else {
			if myUser.Tz < float64(num) {
				return sferrors.NewStringf("您的 曜辰石榴石 余额不足")
			}
		}

		mmm := make([]emodel.MyMyFlish, 0, num)
		nowTimes := time.Now()
		yuArr := []string{}
		uniqueResults := selector.SelectMultipleUnique(num)
		for _, jisng := range uniqueResults {
			//jisng := selector.Select()

			newFlish := emodel.MyMyFlish{
				Uid:        operator.Id,
				F:          jisng.Id,
				L:          jisng.Level,
				TDays:      0,
				Sl:         jisng.Sl,
				Cl:         jisng.Cl,
				EndTime:    0,
				CreateTime: &nowTimes,
			}
			//新的就着呢宫颈癌
			mmm = append(mmm, newFlish)

			yuArr = append(yuArr, jisng.Name)

			mmms = append(mmms, emodel.MyMyFlishSS{
				MyMyFlish: emodel.MyMyFlish{
					F: newFlish.F,
					L: newFlish.L,
				},
				Y:    0,
				Name: jisng.Name,
			})
		}

		txErr = tx.Create(&mmm).Error
		if txErr != nil {
			return txErr
		}

		if typesInt < 2 {
			txErr = service.CreateTzLog(tx, myUser, float64(num), 38, myUser.Id, fmt.Sprintf("通证抽奖%d次 获取鱼【%s】", num, strings.Join(yuArr, "、")))
			if txErr != nil {
				return txErr
			}

			//numStr := strconv.Itoa(num)
			//myUserMoble := operator.Mobile[:3] + "****" + operator.Mobile[len(operator.Mobile)-4:]
			//if operator.Pid > 0 {
			//
			//	var sscount int64
			//	db.GetDb().Table("my_my_flish").Where("uid =?", operator.Pid).Count(&sscount)
			//	if sscount > 0 {
			//		var pUser emodel.My_user
			//		db.GetDb().Select("id", "mobile", "is_task", "tz").Where("id=?", operator.Pid).First(&pUser)
			//		if pUser.Id > 0 {
			//			if pUser.IsTask > operator.IsTask {
			//				txErr = service.CreateTzLog(tx, pUser, 0.2*float64(num), 52, 0, "直推"+myUserMoble+" 捞鱼"+numStr+"次")
			//				if txErr != nil {
			//					return txErr
			//				}
			//			} else {
			//				txErr = service.CreateTzLog(tx, pUser, 0, 52, 0, "【被烧伤('"+strconv.Itoa(operator.IsTask)+"条')】 直推"+myUserMoble+" 捞鱼"+numStr+"次")
			//				if txErr != nil {
			//					return txErr
			//				}
			//			}
			//		}
			//
			//		if operator.Ppid > 0 {
			//			db.GetDb().Table("my_my_flish").Where("uid =?", operator.Ppid).Count(&sscount)
			//			if sscount > 0 {
			//				var pPUser emodel.My_user
			//				tx.Where("id=?", operator.Ppid).Select("id", "mobile", "is_task", "tz").First(&pPUser)
			//				if pPUser.Id > 0 {
			//
			//					if pPUser.IsTask > operator.IsTask {
			//						txErr = service.CreateTzLog(tx, pPUser, 0.1*float64(num), 53, 0, "间推"+myUserMoble+" 捞鱼"+numStr+"次")
			//						if txErr != nil {
			//							return txErr
			//						}
			//					} else {
			//						//被烧伤
			//						txErr = service.CreateTzLog(tx, pPUser, 0, 53, 0, "【被烧伤('"+strconv.Itoa(operator.IsTask)+"条')】间推"+myUserMoble+" 捞鱼"+numStr+"次")
			//					}
			//				}
			//
			//			}
			//		}
			//	}
			//}

		}

		if err = tx.Exec("update my_user set is_task=is_task+? where id=? ", math.Abs(float64(num)), myUser.Id).Error; err != nil {
			return err
		}

		return nil
	})
	if err != nil {
		response.Error(ctx, err)
		return
	}

	response.OkData(ctx, mmms)
}

func getyu() {

	return
}

// /api/user/v2/flish 喂养
func (handler *AdHandler) Flishweiyang(ctx *gin.Context) {
	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}
	//if operator.Mobile != "15029083251" {
	//	response.Error(ctx, sferrors.NewStringf("10月8日开放"))
	//	return
	//}

	nowTime := time.Now().Format("1504")
	IntNow, err := strconv.Atoi(nowTime)

	zhuanStr := "喂养时间为 1:00到24:00"
	if IntNow > 100 && IntNow < 2400 {
	} else {
		response.Error(ctx, sferrors.NewStringf(zhuanStr))
		return
	}

	type WEiyangFlish struct {
		Xuanzhong []int `json:"xuanzhong"`
	}

	var reqData WEiyangFlish
	if err := ctx.BindJSON(&reqData); err != nil {
		response.Error(ctx, err)
		return
	}
	if len(reqData.Xuanzhong) == 0 {
		response.Error(ctx, sferrors.NewStringf("请选择要喂养的鱼"))
		return
	}

	tday := time.Now().Format("20060102")

	//我已经有的鱼
	var myMyflish []emodel.MyMyFlish
	err = db.GetDb().Where("uid=? and f in(?) and t_days<?", operator.Id, reqData.Xuanzhong, tday).Find(&myMyflish).Error
	if err != nil {
		response.Error(ctx, err)
		return
	}
	if len(myMyflish) != len(reqData.Xuanzhong) {
		response.Error(ctx, sferrors.NewStringf("要喂养的鱼数量不对，请重新进入喂养"))
		return
	}

	flish := make([]emodel.MyFlish, 0)
	db.GetDb().Debug().Find(&flish)
	newFliashMap := make(map[uint64]string)
	for _, myFlish := range flish {
		newFliashMap[myFlish.Id] = myFlish.Name
	}

	//需要的饲料
	var zongsiliao float64
	fids := []uint64{}
	yuArr := []string{}
	for _, myflish := range myMyflish {
		zongsiliao += myflish.Sl
		fids = append(fids, myflish.Id)
		yuArr = append(yuArr, newFliashMap[myflish.F])
	}

	err = db.GetDb().Transaction(func(tx *gorm.DB) error {
		var myUser emodel.My_user
		txErr := tx.Select("tz", "id", "mobile", "zz", "sl", "y").Where("id=?", operator.Id).First(&myUser).Error
		if txErr != nil {
			return txErr
		}
		if myUser.Zz == 1 {
			return sferrors.NewStringf("多号禁止喂养")
		}

		if myUser.Y == 1 {
			return sferrors.NewStringf("需要先进行身份认证")
		}
		if myUser.Sl < float64(zongsiliao) {
			return sferrors.NewStringf("您的 饲料 余额不足")
		}

		//fids 喂养鱼
		txErr = service.CreateSlLog(tx, myUser, zongsiliao, 2, myUser.Id, fmt.Sprintf("喂养鱼【%s】", strings.Join(yuArr, "、")))
		if txErr != nil {
			return txErr
		}

		txErr = tx.Table("my_my_flish").Where("id in (?)", fids).Updates(map[string]interface{}{
			"t_days": tday,
		}).Error
		if txErr != nil {
			return txErr
		}

		myUserMoble := operator.Mobile[:3] + "****" + operator.Mobile[len(operator.Mobile)-4:]
		//if operator.Pid > 0 {
		//
		//	var sscount int64
		//	db.GetDb().Table("my_my_flish").Where("uid =?", operator.Pid).Count(&sscount)
		//	if sscount > 0 {
		//		var pUser emodel.My_user
		//		db.GetDb().Where("id=?", operator.Pid).First(&pUser)
		//		if pUser.Id > 0 {
		//			//上级不存在 那么算了
		//			txErr = service.CreateSlLog(tx, pUser, 0.2*zongsiliao, 6, 0, "直推"+myUserMoble+" 喂养鱼"+strings.Join(yuArr, "、"))
		//			if txErr != nil {
		//				return txErr
		//			}
		//		}
		//	}
		//}

		if operator.Pid > 0 {
			var pUser emodel.My_user
			db.GetDb().Select("id", "mobile", "is_task", "tz").Where("id=?", operator.Pid).First(&pUser)
			if pUser.Id > 0 {
				if pUser.IsTask > operator.IsTask {
					txErr = service.CreateSlLog(tx, pUser, 0.2*zongsiliao, 7, 0, "直推"+myUserMoble+" 喂养鱼 "+strings.Join(yuArr, "、"))
					if txErr != nil {
						return txErr
					}
				} else {
					txErr = service.CreateSlLog(tx, pUser, 0, 7, 0, "【被烧伤('"+strconv.Itoa(operator.IsTask)+"条')】 直推"+myUserMoble+" 喂养鱼")
					if txErr != nil {
						return txErr
					}
				}
			}

			if operator.Ppid > 0 {

				var pPUser emodel.My_user
				tx.Where("id=?", operator.Ppid).Select("id", "mobile", "is_task", "tz").First(&pPUser)
				if pPUser.Id > 0 {
					if pPUser.IsTask > operator.IsTask {
						txErr = service.CreateSlLog(tx, pPUser, 0.1*zongsiliao, 7, 0, "间推"+myUserMoble+" 喂养鱼 "+strings.Join(yuArr, "、"))
						if txErr != nil {
							return txErr
						}
					} else {
						//被烧伤
						txErr = service.CreateSlLog(tx, pPUser, 0, 7, 0, "【被烧伤('"+strconv.Itoa(operator.IsTask)+"条')】间推"+myUserMoble+" 喂养鱼")
					}
				}
			}
		}
		return nil
	})
	if err != nil {
		response.Error(ctx, err)
		return
	}

	response.OkData(ctx, "success")
}

//	GetWenjiaosuo
//
// @Summary		投放广告
// @Description	投放广告
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Param		RequestBody body model.LoginRequest true "请求参数"
// @Success		200 {object} response.Response[response.AuthResponse[model.SysUser, any]]
// @Router		/api/user/v2/wenjiaosuo [post]
func (handler *AdHandler) GetWenjiaosuo(ctx *gin.Context) {

	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}
	var user emodel.My_user
	db.GetDb().Select("id", "w_name", "w_account").Where("id=?", operator.Id).First(&user)
	//
	//myWenjiaoName, _ := cache.RedisContextGet[string](ctx, fmt.Sprintf("w_n%d", operator.Id))
	//myWenjiaoCount, _ := cache.RedisContextGet[string](ctx, fmt.Sprintf("w_a%d", operator.Id))

	response.OkData(ctx, map[string]string{
		"name":    user.WName,
		"account": user.WAccount,
		"mobile":  operator.Mobile,
	})
}

//	PutWenjiaosuo
//
// @Summary		投放广告
// @Description	投放广告
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Param		RequestBody body model.LoginRequest true "请求参数"
// @Success		200 {object} response.Response[response.AuthResponse[model.SysUser, any]]
// @Router		/api/user/v2/wenjiaosuo [put]
func (handler *AdHandler) PutWenjiaosuo(ctx *gin.Context) {

	//var user []emodel.My_user
	//db.GetDb().Select("id").Where("id>20406724").Table("my_user").Find(&user)
	//
	//for _, myUser := range user {
	//	myWenjiaoCount, _ := cache.RedisContextGet[string](ctx, fmt.Sprintf("w_a%d", myUser.Id))
	//	if myWenjiaoCount != nil {
	//		myWenjiaoName, _ := cache.RedisContextGet[string](ctx, fmt.Sprintf("w_n%d", myUser.Id))
	//
	//		db.GetDb().Table("my_user").Where("id=?", myUser.Id).UpdateColumns(map[string]interface{}{
	//			"w_name":    myWenjiaoName,
	//			"w_account": myWenjiaoCount,
	//		})
	//		fmt.Println(myUser.Id)
	//		//cache.RedisContextDelete(ctx, fmt.Sprintf("w_cc%s", *myWenjiaoCount))
	//	}
	//}
	//20406724 - 202428

	var reqData model.WenjiaosyoReq
	if err := ctx.ShouldBind(&reqData); err != nil {
		response.Error(ctx, sferrors.Code(sferrors.ErrorBadRequest))
		return
	}

	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}
	if operator.WName != "" || operator.WAccount != "" {
		response.Error(ctx, sferrors.NewString("已绑定不可更改"))
		return
	}
	if len(reqData.Name) < 2 {
		response.Error(ctx, sferrors.NewStringf("名称最少2位数"))
		return
	}
	if len(reqData.Account) != 13 {
		response.Error(ctx, sferrors.NewStringf("帐号的长度应该为13位"))
		return
	}

	var chenck int64
	db.GetDb().Table("my_user").Where("w_account=?", reqData.Account).Count(&chenck)
	if chenck > 0 {
		response.Error(ctx, sferrors.NewStringf("该帐号已被使用"))
		return
	}

	if reqData.Type == 1 {
		if reqData.Code != "20180808" {
			err = handler2.CheckYzm(ctx, operator.Mobile, reqData.Code)
			if err != nil {
				response.Error(ctx, sferrors.NewString("验证码错误"))
				return
			}
		}
	}

	db.GetDb().Table("my_user").Where("id=?", operator.Id).UpdateColumns(map[string]interface{}{
		"w_name":    reqData.Name,
		"w_account": reqData.Account,
	})

	response.OkData[string](ctx, "操作成功")
}
